<template>
    <div class="view">
        <android-nav-bar title="我的相册" v-on:back="mineAlbumBack"></android-nav-bar>
        <cube-scroll class="scroll" ref="scroll" :scroll-events="['scroll']">
            <div class="upload-img-box">
                <cube-upload v-if="!device.status" accept="image/*" ref="upload" v-model="files" @files-added="addFiles" @file-success="addFilesSucc" :action="uploadOption()" class="upload-headImg">
                    <cube-upload-btn :multiple="false">
                        <cube-upload-file v-for="(file, i) in files" :file="file" :key="i"></cube-upload-file>
                        <div class="none-img flex" v-show="!user.avatar && files.length <= 0">
                            <span class="iconfont icon-ren"></span>
                            <span class="iconfont icon-plus"></span>
                            <span class="tip-none">点这 <br> 上传头像</span>
                        </div>
                        <div class="has-img" v-if="user.avatar && files.length <= 0" :style="`background:url(${user.avatar.filePath}?imageView2/0/h/150/interlace/1) no-repeat;backgroundSize:100% 100%;backgroundPosition:0 0;`">
                            <!--                            <img :src="user.avatar.filePath">-->
                            <p class="state-tip">头像及邂逅照</p>
                        </div>
                    </cube-upload-btn>
                </cube-upload>
                <div v-else class="app-upload-face" :style="{'background-image':`url(${user.avatar.filePath}?imageView2/0/h/150/interlace/1)`}" @click="appFaceSelected">
                    <p class="state-tip">头像及邂逅照</p>
                </div>
            </div>
            <div class="upload-img flex">
                <cube-upload v-if="!device.status" ref="uploadPhoto" v-model="photoFiles" @files-added="addPhotoFiles" @file-success="addPhotoFilesSucc" :action="uploadOption('photo')">
                    <cube-upload-btn class="add-photo flex">
                        <span class="iconfont icon-plus"></span><span>添加照片</span>
                    </cube-upload-btn>
                </cube-upload>
                <div class="app-upload-photo" v-else @click="appPhotoSelected">
                    <span class="iconfont icon-plus"></span><span>添加照片</span>
                </div>
                <div class="photo" v-for="item in this.user.photo" :style="`background-image:url(${item.uploadfile.file_path}?imageView2/0/h/170/interlace/1);`">
                    <p class="delete" @click="detelePhoto(item.id)">×</p>
                    <p class="state-tip" v-if="item.uploadfile.file_status.status==0">审核中</p>
                </div>
            </div>
        </cube-scroll>
    </div>
</template>

<script lang="ts">
    import {Component, Vue, Watch} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";

    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";
    import CommonUnit from "@/unit/CommonUnit";
    import {updateUser} from "@/store/dispatches";
    import UserEntity from "@/entity/UserEntity";
    import AndroidNavBar from "@/components/aui/AndroidNavBar.vue";


    @Component({
        components: {
            AndroidNavBar
        }
    })
    export default class MineAlbum extends Scene {
        private publicPath: string = process.env.BASE_URL;

        @State("UserStore")
        public user!: InterfaceUser;

        @State("DeviceStore")
        private device!: any;

        private files: [] = [];
        private photoFiles: [] = [];
        private uploadTimes: number = 0;

        private uploadOption(type: string = "header"): any {
            let uploadOption: any = {};
            uploadOption.target = this.api.imageUpload;
            uploadOption.fileName = "iFile";
            uploadOption.data = {type: "header"};
            uploadOption.headers = {token: this.user.token};
            uploadOption.checkSuccess = (res: any, file: any) => {
                return res.code == 1;
            };
            return uploadOption;
        }

        private addFiles(): void {
            const file = (<any> this).files[0];
            file && (<any> this).$refs.upload.removeFile(file);
        }

        private addPhotoFiles(): void {
            const file = (<any> this).photoFiles[0];
            file && (<any> this).$refs.uploadPhoto.removeFile(file);
        }

        private get saveParams(): any {
            if (this.files.length > 0) {
                let user = new UserEntity(Object.assign(this.user, {avatarId: (<any> this).files[0].response.data.id})).getBaseInfo;
                delete user.gender;
                delete user.birthday;

                return user;
            }
            return {};
        }

        private addFilesSucc(): void {
            this.updateUserFace(this.saveParams);
        }

        private addPhotoFilesSucc(): void {
            if (this.uploadTimes < this.photoFiles.length - 1) {
                this.uploadTimes++;
            } else if (this.uploadTimes == this.photoFiles.length - 1) {
                let photoId: number[] = [];
                for (let i in this.photoFiles) {
                    let id: number = Number((<any> this).photoFiles[i].response.data.id);
                    photoId.push(id);
                }
                let id: string = String(photoId);
                Http.post(this.api.addPhoto, {ids: id}, {token: this.user.token}).then((res) => {
                    if (res.code == 1) {
                        this.photoFiles = [];
                        this.uploadTimes = 0;
                        (<any> this).$createToast({
                            txt: `上传成功`,
                            type: "correct",
                            time: 1000
                        }).show();
                        Http.get(this.api.getUserInfo, {}, {token: this.user.token}).then((res) => {
                            let user: any = {...res.data, ...res.data.user_info};
                            delete user.user_info;
                            updateUser(CommonUnit.objectUnderlineToHump(user));
                        });
                    } else if (res.code == 0) {
                        this.photoFiles = [];
                        (<any> this).$createToast({
                            txt: `${res.msg}`,
                            type: "warn",
                            time: 1000
                        }).show();
                    }
                });
            }
        }

        private detelePhoto(id: number): void {
            Http.get(this.api.deletePhoto, {id: id}, {token: this.user.token}).then((res) => {
                if (res.code == 1) {
                    (<any> this).$createToast({
                        txt: `删除成功`,
                        type: "correct",
                        time: 1000
                    }).show();
                    Http.get(this.api.getUserInfo, {}, {token: this.user.token}).then((res) => {
                        let user: any = {...res.data, ...res.data.user_info};
                        delete user.user_info;
                        updateUser(CommonUnit.objectUnderlineToHump(user));
                    });
                } else if (res.code == 0) {
                    (<any> this).$createToast({
                        txt: `删除失败,稍后再试!`,
                        type: "warn",
                        time: 1000
                    }).show();
                }
            });
        }

        private mineAlbumBack(): void {
            this.navigateBack();
        }

        private mounted(): void {

        }

        private showAppUploadSource(cbType: number = 1): void {
            (<any> this).$createActionSheet({
                data: [
                    {
                        content: "从相册中选择",
                        sourceType: "PHOTOLIBRARY"
                    },
                    {
                        content: "拍摄",
                        sourceType: "CAMERA"
                    },

                ],
                onSelect: (item: any, index: any) => {
                    if (this.device.status) {
                        let toast = (<any> this).$createToast({
                            time: 0,
                            txt: item.sourceType === "CAMERA" ? "初始化相机" : "打开系统相册",
                            mask: true
                        }).show();
                        let cameraOptions = {
                            quality: 75,
                            destinationType: Camera.DestinationType.FILE_URI,
                            sourceType: item.sourceType === "CAMERA" ? Camera.PictureSourceType.CAMERA : Camera.PictureSourceType.PHOTOLIBRARY,     //照相机类型
                            allowEdit: true,
                            encodingType: Camera.EncodingType.JPEG,
                            saveToPhotoAlbum: false,
                        };
                        (<any> navigator).camera.getPicture((img: string) => {
                            if (cbType === 1) {
                                this.uploadFaceImage(img);
                            } else if (cbType === 2) {
                                this.uploadPhotoAlbumImage(img);
                            }
                        }, ((error: any) => {
                            toast.hide();
                        }), cameraOptions);
                        toast.hide();
                    }

                }
            }).show();
        }

        private appFaceSelected(): void {
            this.showAppUploadSource(1);
        }

        private uploadPhotoAlbumImage(img: string): void {
            let toast = (<any> this).$createToast({
                time: 0,
                txt: "正在上传",
                mask: true
            }).show();

            Http.uploadNative(this.api.imageUpload, img, {type: "photo"}, {token: this.user.token}).then((res) => {
                if (res.code === 1) {
                    Http.post(this.api.addPhoto, {ids: res.data.id}, {token: this.user.token}).then((res) => {
                        if (res.code == 1) {
                            Http.get(this.api.getUserInfo, {}, {token: this.user.token}).then((res) => {
                                let user: any = {...res.data, ...res.data.user_info};
                                delete user.user_info;
                                updateUser(CommonUnit.objectUnderlineToHump(user));
                                (<any> this).$createToast({
                                    txt: `上传成功`,
                                    type: "correct",
                                    time: 1000
                                }).show();
                            });
                        } else if (res.code == 0) {
                            (<any> this).$createToast({
                                txt: `${res.msg}`,
                                type: "warn",
                                time: 1000
                            }).show();
                        }
                    });
                } else {
                    toast = (<any> this).$createToast({
                        time: 2000,
                        txt: res.msg,
                        mask: true,
                        type: "error"
                    }).show();
                }
            }).catch((e: any) => {
                toast = (<any> this).$createToast({
                    time: 2000,
                    txt: "网络出错",
                    mask: true,
                    type: "error"
                }).show();
            });
        }

        private uploadFaceImage(img: string): void {
            let toast = (<any> this).$createToast({
                time: 0,
                txt: "正在上传",
                mask: true
            }).show();

            Http.uploadNative(this.api.imageUpload, img, {type: "header"}, {token: this.user.token}).then((res) => {
                if (res.code === 1) {
                    let userBaseInfo = new UserEntity(Object.assign(this.user, {avatarId: res.data.id})).getBaseInfo;
                    delete userBaseInfo.gender;
                    delete userBaseInfo.birthday;
                    this.updateUserFace(userBaseInfo, toast);
                } else {
                    toast = (<any> this).$createToast({
                        time: 2000,
                        txt: res.msg,
                        mask: true,
                        type: "error"
                    }).show();
                }
            }).catch((e: any) => {
                toast = (<any> this).$createToast({
                    time: 2000,
                    txt: "网络出错",
                    mask: true,
                    type: "error"
                }).show();
            });
        }

        private updateUserFace(userBaseInfo: any, toast: any = ""): void {
            Http.post(this.api.saveBaseInfo, userBaseInfo, {token: this.user.token}).then((res) => {
                if (res.code == 1) {
                    Http.get(this.api.getUserInfo, {}, {token: this.user.token}).then((res) => {
                        let user: any = {...res.data, ...res.data.user_info};
                        delete user.user_info;
                        updateUser(CommonUnit.objectUnderlineToHump(user));
                        toast = (<any> this).$createToast({
                            txt: `上传成功`,
                            type: "correct",
                            time: 1000
                        }).show();
                    });
                } else if (res.code == 0) {
                    toast = (<any> this).$createToast({
                        txt: `${res.msg}`,
                        type: "warn",
                        time: 1000
                    }).show();
                }
            }).catch((e) => {
                toast = (<any> this).$createToast({
                    txt: "上传失败",
                    type: "error",
                    time: 1000
                }).show();
            });
            setTimeout(() => {
                toast.hide();
            }, 1000);
        }

        private appPhotoSelected(): void {
            this.showAppUploadSource(2);
        }
    }
</script>

<style scoped lang="stylus">
    .view
        position relative;
        width 100vw;
        height 100vh;
        overflow hidden
        background $theme-page-common-background-color;

        .scroll
            height 100vh;
            padding-bottom  var(--safe-area-inset-bottom);

        .upload-img-box
            width 100vw;
            height 140px;
            background #fff;
            position relative;
            margin-top calc(47px + var(--safe-area-inset-top));

            &::before
                display table;
                content '';

            &::after
                display table;
                content '';
                position absolute;
                width 60vw;
                height 3px;
                border-radius 20px;
                left 20vw;
                bottom 0;
                background linear-gradient(to right, rgba(254, 124, 79, .6), rgba(255, 89, 163, .6));

            .upload-headImg, .app-upload-face
                width 120px;
                height 120px;
                margin 10px auto;
                text-align center;

                .state-tip
                    width 100%;
                    height 20px;
                    line-height 20px;
                    color $theme-viceColor-font;
                    font-size 10px;
                    background-color rgba(255, 255, 255, .5);
                    position absolute;
                    bottom 0;
                    left 0;

                >>> .cube-upload-file, .cube-upload-btn
                    width 120px;
                    height 120px;

                    .cube-upload-file-def
                        width 100%;
                        height 100%;

                    .cubeic-wrong
                        display none;

                    .cube-upload-file_stat
                        background-color transparent;

                    .cube-upload-file-progress
                        //color $theme-viceColor-font;
                    .cube-upload-file-status.cubeic-right
                        display none;

                .has-img
                    position relative;
                    text-align center;
                    width 120px;
                    height 120px;
                    background-position center;
                    background-size 100%;

                    img
                        display block;
                        width 100%;
                        height 100%;

                    .state-tip
                        width 100%;
                        height 20px;
                        line-height 20px;
                        color $theme-viceColor-font;
                        font-size 10px;
                        background-color rgba(255, 255, 255, .5);
                        position absolute;
                        bottom 0;
                        left 0;

                .none-img
                    position relative;
                    width 100%;
                    height 100%;
                    background-color $theme-page-common-background-color;
                    justify-content: center;
                    align-items flex-end;
                    text-align center;

                    span.icon-ren
                        color #fff;
                        font-size 90px;

                    span.icon-plus
                        position absolute;
                        bottom 25px;
                        right 20px;
                        color #fff;
                        padding 3px;
                        border-radius 50%;
                        background linear-gradient(to right, rgba(254, 124, 79, .6), rgba(255, 89, 163, .6));

                    span.tip-none
                        position absolute;
                        font-size 12px;
                        color $theme-page-common-background-color;
                        padding-bottom 6px;
                        line-height 1.3em;

        div.upload-img
            flex-wrap wrap;
            margin-top 15px;

            >>> .cubeic-wrong
                display none;

            >>> .cube-upload-file-state
                display none;


            div.add-photo, div.app-upload-photo
                width calc(100vw / 3);
                height calc(100vw / 3);
                flex-wrap wrap;
                text-align center;
                align-content center;
                color $theme-viceColor-font;
                border 1px dashed $theme-viceColor-font;
                border-radius 5px;

                > span
                    display inline-block;
                    width calc(100vw / 3);

                span.icon-plus
                    font-size 50px;
                    margin-bottom 5px;

            div.photo
                position relative;
                text-align center;
                width calc(100vw / 3);
                height calc(100vw / 3);
                background-position center;
                background-size cover;

                .delete
                    width 20px;
                    height 20px;
                    line-height 20px;
                    position absolute;
                    font-size 24px;
                    top 0px;
                    right 0px;
                    background-color #fff;
                    color $theme-viceColor-font;

                img
                    display block;
                    width 100%;
                    height 100%;

                .state-tip
                    width 100%;
                    height 20px;
                    line-height 20px;
                    color $theme-viceColor-font;
                    font-size 10px;
                    background-color rgba(255, 255, 255, .5);
                    position absolute;
                    bottom 0;
                    left 0;

    .app-upload-face
        position relative;
        background-position center;
        background-size cover;

    .app-upload-photo
        width 33.33vw;
        height 33.33vw
        color #9d9d9d;
        border 1px dashed #9d9d9d;
        display flex;
        flex-direction column;
        justify-content center;
        align-items center;
        border-radius 3px;
</style>
